/**
 * 
 */
package com.cait.dutyfree.test;

import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

/**
 * @author Rasika Kaluwalgoda
 *
 */
public class MonitorThread implements Runnable {

    private static Logger log = Logger.getLogger(MonitorThread.class);
    boolean interruped;
    private long checkIntervalMillis = 10000;
    private String url;
    private File file;

    // stores the last modification time of the file
    private long lastModified = 0;

    public void run() {
		file = new File(url);
		DOMConfigurator.configure(url);
		lastModified = file.lastModified();
	
		monitor();
    }

    @SuppressWarnings("static-access")
	private void monitor() {
    	log.info("Starting log4j monitor");
 
		while (!interruped) {
	
		    // check if File changed
		    long temp = file.lastModified();
		    if (lastModified != temp) {
		    	log.info("Initialize log4j configuration " + url);
		    	DOMConfigurator.configure(url);
	
		    	lastModified = temp;
	
		    } else
		    	log.debug("Log4j configuration is not modified");
		    try {
		    	Thread.currentThread().sleep(checkIntervalMillis);
		    } catch (InterruptedException e) {
		    	interruped = true;
		    }
		}
		log.info("Shutting down log4j monitor");

    }

    public String getUrl() {
    	return url;
    }

    public void setUrl(String url) {
    	this.url = url;
    }

    public long getCheckIntervalMillis() {
    	return checkIntervalMillis;
    }

    public void setCheckIntervalMillis(long checkIntervalMillis) {
    	this.checkIntervalMillis = checkIntervalMillis;
    }

    public boolean isInterruped() {
    	return interruped;
    }

    public void setInterruped(boolean interruped) {
    	this.interruped = interruped;
    }

}
